package com.integral.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.integral.biz.IBalanceBiz;
import com.integral.biz.IBankBiz;
import com.integral.biz.IBankExchangeRateBiz;
import com.integral.biz.IBankTypeBiz;
import com.integral.biz.IBannerImgBiz;
import com.integral.biz.IDeclarationBiz;
import com.integral.biz.IOrderBiz;
import com.integral.biz.IProductBiz;
import com.integral.biz.IUserBiz;
import com.integral.biz.IUserTypeBiz;
import com.integral.constant.OrderConstant;
import com.integral.constant.UserTypeCode;
import com.integral.entity.Balance;
import com.integral.entity.BankType;
import com.integral.entity.Declaration;
import com.integral.entity.Order;
import com.integral.entity.User;
import com.integral.service.IntegralPortService;
import com.integral.util.SmsUtil;
import com.integral.util.UploadImgUtil;
import com.integral.vo.BankExchangeRateVo;
import com.integral.vo.BankTypeVo;
import com.integral.vo.BankVo;
import com.integral.vo.BannerImgVo;
import com.integral.vo.DeclarationVo;
import com.integral.vo.IntegralBankExchangeReateVo;
import com.integral.vo.IntegralPortVo;
import com.integral.vo.ProductVo;
import com.integral.vo.UserVo;

@Controller
@RequestMapping("/integralPortController")
public class IntegralPortController {

	//注入小程序Service
	@Resource
	private IntegralPortService integralPortService;
	//注入用户Biz
	@Resource
	private IUserBiz userBiz;
	//注入用户类型
	@Resource
	private IUserTypeBiz userTypeBiz;
	//注入银行产品
	@Resource
	private IBankTypeBiz bankTypeBiz;
	//注入银行
	@Resource
	private IBankBiz bankBiz;
	//注入银行汇率
	@Resource
	private IBankExchangeRateBiz bankExchangeRateBiz;
	//注入轮播图
	@Resource
	private IBannerImgBiz bannerImgBiz;
	//注入报单
	@Resource
	private IDeclarationBiz declarationBiz;
	//注入用户余额
	@Resource
	private IBalanceBiz balanceBiz;
	//注入订单
	@Resource
	private IOrderBiz orderBiz;
	//注入支付产品
	@Resource
	private IProductBiz productBiz;
	
	/*
	 * 用户授权成功后，修改用户昵称
	 */
	@RequestMapping(value="/updateUserName")
	@ResponseBody
	public String updateUserName(User user){
		if(StringUtils.isEmpty(user.getUserCode())){
			return null;
		}
		User wxUser = userBiz.findByCode(user.getUserCode());
		if(null == wxUser){
			return null;
		}
		wxUser.setUserName(user.getUserName());
		userBiz.updateUser(wxUser);
		return "修改成功！";
	}
	/**
	 * 获取所有银行信息
	 * @return
	 */
	@RequestMapping(value="/findIndexAll")
	@ResponseBody
	public Object findIndexAll(IntegralPortVo integralPortVo){
		//根据用户唯一标识查询用户
		//暂时传入用户类别编码。后期传入用户唯一标识，获取用户类别编码
//		User user = userBiz.findByUserOpenid(integralPortVo.getUserOpenid());
//		integralPortVo.setUserTypeCode(user.getUserTypeCode());
		
		List<IntegralPortVo> list = integralPortService.findIndexAll(integralPortVo);
		return list;
	}
	/**
	 * 获取银行产品
	 * @param bankTypeVo
	 * @return
	 */
	@RequestMapping(value="/findBankType")
	@ResponseBody
	public List<BankTypeVo> findBankType(BankTypeVo bankTypeVo){
		return bankTypeBiz.findBankType(bankTypeVo);
	}
	
	/**
	 * 获取银行汇率
	 * @param bankExchangeRateVo
	 * @return
	 */
	@RequestMapping(value="/findExchangeFate")
	@ResponseBody
	public List<IntegralBankExchangeReateVo> findExchangeFate(BankExchangeRateVo bankExchangeRateVo){
		List<IntegralBankExchangeReateVo> datas = new ArrayList<IntegralBankExchangeReateVo>();
		//封装查询参数
		BankVo bankVo = new BankVo();
		bankVo.setDeleteFlag(0);
		bankVo.setStart(null);
		bankVo.setPageSize(null);
		//查询所有银行
		List<BankVo> bankList = bankBiz.findBank(bankVo);
		for (BankVo bankVo2 : bankList) {
			//获取用户价格
			IntegralBankExchangeReateVo data = findExchangeFateByBankCode(bankVo2);
			if(null != data){
				datas.add(data);
			}
		}
		return datas;
	}
	/**
	 * 根据银行编码查询银行汇率,获取用户价格
	 * @param bankTypeVo
	 */
	private IntegralBankExchangeReateVo findExchangeFateByBankCode(BankVo bankVo){
		IntegralBankExchangeReateVo data = new IntegralBankExchangeReateVo();
		
		//设置银行产品查询条件
		BankTypeVo bankTypeVo = new BankTypeVo();
		bankTypeVo.setBankCode(bankVo.getBankCode());
		bankTypeVo.setDeleteFlag(0);
		bankTypeVo.setStart(null);
		bankTypeVo.setPageSize(null);
		//根据银行编码，所需积分查询银行产品
		BankType bankType = bankTypeBiz.findBankTypeByBankCode(bankTypeVo);
		if(null == bankType){
			return null;
		}
		//所需积分
		data.setInceptionUnit(bankType.getIntegralNo());
		//银行编码
		data.setBankCode(bankVo.getBankCode());
		//银行名称
		data.setBankName(bankVo.getBankName());
		//查询银行汇率信息
		BankExchangeRateVo bankExchangeRateVo = new BankExchangeRateVo();
		bankExchangeRateVo.setBankCode(bankVo.getBankCode());
		bankExchangeRateVo.setDeleteFlag(0);
		bankExchangeRateVo.setStart(null);
		bankExchangeRateVo.setPageSize(null);
		List<BankExchangeRateVo> list = bankExchangeRateBiz.findBankExchangeRate(bankExchangeRateVo);
		if(list.isEmpty()){
			return null;
		}
		for (BankExchangeRateVo bankExchangeRateVo2 : list) {
			//获取银行汇率
			BigDecimal exchangeRate = bankExchangeRateVo2.getBankExchangeRate();
			//获取最终兑换金额（产品回购价格*银行汇率，保留2位小数，四舍五入）
			BigDecimal money = bankVo.getInceptionUnit().multiply(exchangeRate).setScale(2, BigDecimal.ROUND_HALF_UP);
			switch (bankExchangeRateVo2.getUserTypeCode()) {
			case UserTypeCode.USER_CODE:
				//银行产品回购价格*银行汇率 = 用户价格
				data.setUserExchangeReate(money.doubleValue());
				break;
			case UserTypeCode.VIP_CODE:
				//银行产品回购价格*银行汇率 = 用户价格
				data.setVipExchangeReate(money.doubleValue());
				break;
			case UserTypeCode.GOLD_CODE:
				//银行产品回购价格*银行汇率 = 用户价格
				data.setGoldExchangeReate(money.doubleValue());
				break;
			default:
				break;
			}
		}
		return data;
	}
	/**
	 * 获取轮播图
	 * @return
	 */
	@RequestMapping(value="/findIndexBanner")
	@ResponseBody
	public List<BannerImgVo> findIndexBanner(BannerImgVo bannerImgVo){
		bannerImgVo.setStart(null);
		bannerImgVo.setPageSize(null);
		List<BannerImgVo> list = bannerImgBiz.findBannerImg(bannerImgVo);
		return list;
	}
	/**
	 * 根据openId查询用户
	 * @return
	 */
	@RequestMapping(value="/findUserByOpenId")
	@ResponseBody
	public UserVo findUserByOpenId(String userOpenId){
		return userBiz.findByUserOpenid(userOpenId);
	}
	/**
	 * 新增报单
	 * @param request
	 * @param declarationVo
	 */
	@RequestMapping(value="/addDeclaration")
	@ResponseBody
	public void addDeclaration(DeclarationVo declarationVo,HttpServletRequest request){
		Declaration declaration = new Declaration();
		//用户唯一标识
		declaration.setUserOpenid(declarationVo.getUserOpenid());
		//银行产品类别编码
		declaration.setBankTypeCode(declarationVo.getBankTypeCode());
		//兑换编码
		declaration.setDeclarationExchangeCode(declarationVo.getDeclarationExchangeCode());
		//报单数量
		declaration.setDeclarationNum(declarationVo.getDeclarationNum() < 1?1:declarationVo.getDeclarationNum());
		//备注
		declaration.setRemark(declarationVo.getRemark());
		//上传文件
		declaration.setDeclarationImg(declarationVo.getDeclarationImg());
		//上传文件
		/*String fileName = UploadImgUtil.dowloadFile(declarationVo.getUploadImg(), request);
		if("false".equals(fileName)){
			declaration.setDeclarationImg(null);
		}else{
			declaration.setDeclarationImg(fileName);
		}*/
		declarationBiz.addDeclaration(declaration);
	}
	
	/**
	 * 根据订单编码修改订单状态（修改订单状态，并设置用户类别）
	 * @param orderNo
	 * @param orderStatus
	 */
	@RequestMapping(value="/updateOrderStatus")
	@ResponseBody
	public void updateOrderStatus(String orderNo,int orderStatus,String openid,int productId){
		//修改订单状态
		Order order = new Order();
		order.setOrderNo(orderNo);
		order.setOrderStatus(orderStatus);
		orderBiz.updateByStatus(order);
		//充值成功
		if(orderStatus == OrderConstant.ORDER_STATUS_SUCCESS){
			//修改用户类型（查询用户奖励，并修改余额）
			User user = new User();
			user.setUserOpenid(openid);
			if(productId == 1){
				user.setUserTypeCode(UserTypeCode.VIP_CODE);
			}else if(productId == 2){
				user.setUserTypeCode(UserTypeCode.GOLD_CODE);
			}
			userBiz.updateByUserType(user);
			//充值上级返利
			superiorUser(openid, productId);
		}
	}
	/**
	 * 充值返利（三级返利）
	 * @param openId
	 * @param productId
	 */
	private void superiorUser(String openId,int productId){
		//根据openId查询用户
		UserVo user = userBiz.findByUserOpenid(openId);
		if(null != user && !StringUtils.isEmpty(user.getUserSuperiorCode())){
			/** 一级返利 */
			User superiorUserOne = userBiz.findByCode(user.getUserSuperiorCode());
			if(null == superiorUserOne){
				return;
			}
			//上级用户类型为普通时则不返利
			if(superiorUserOne.getUserTypeCode() == UserTypeCode.USER_CODE){
				return;
			}
			//根据产品ID查询支付产品
			ProductVo productVo = productBiz.findById(productId);
			if(null == productVo){
				return;
			}
			//查询上级用户余额
			Balance balanceOne = balanceBiz.findByUserCode(superiorUserOne.getUserCode());
			if(null == balanceOne){
				return;
			}
			//设置修改余额
			balanceOne.setUserMoney(balanceOne.getUserMoney().add(productVo.getRebateOne()));
			//修改余额（返利）
			balanceBiz.updateBalance(balanceOne);
			//新增订单
			addOrder(superiorUserOne,productVo.getRebateOne());
			
			/** 二级返利 */
			User superiorUserTwo = userBiz.findByCode(superiorUserOne.getUserSuperiorCode());
			if(null == superiorUserTwo){
				return;
			}
			//上级用户类型为普通时则不返利
			if(superiorUserTwo.getUserTypeCode() == UserTypeCode.USER_CODE){
				return;
			}
			//查询上级用户余额
			Balance balanceTwo = balanceBiz.findByUserCode(superiorUserTwo.getUserCode());
			if(null == balanceTwo){
				return;
			}
			//设置修改余额
			balanceTwo.setUserMoney(balanceTwo.getUserMoney().add(productVo.getRebateTwo()));
			//修改余额（返利）
			balanceBiz.updateBalance(balanceTwo);
			//新增订单
			addOrder(superiorUserTwo,productVo.getRebateTwo());
			
			/** 三级返利 */
			User superiorUserThree = userBiz.findByCode(superiorUserTwo.getUserSuperiorCode());
			if(null == superiorUserThree){
				return;
			}
			//上级用户类型为普通时则不返利
			if(superiorUserThree.getUserTypeCode() == UserTypeCode.USER_CODE){
				return;
			}
			//查询上级用户余额
			Balance balanceThree = balanceBiz.findByUserCode(superiorUserThree.getUserCode());
			if(null == balanceThree){
				return;
			}
			//设置修改余额
			balanceThree.setUserMoney(balanceThree.getUserMoney().add(productVo.getRebateThree()));
			//修改余额（返利）
			balanceBiz.updateBalance(balanceThree);
			//新增订单
			addOrder(superiorUserThree,productVo.getRebateThree());
		}
	}
	/**
	 * 产生订单
	 */
	private void addOrder(User superiorUser,BigDecimal money){
		//产生订单
		String orderNo = "D"+com.integral.util.StringUtils.getRandomStringByLength(5)+new Date().getTime();
		Order order = new Order();
		order.setOrderNo(orderNo);
		order.setExchangeMoney(money);
		order.setOrderStatus(OrderConstant.ORDER_STATUS_SUCCESS);
		order.setOrderType(OrderConstant.ORDER_TYPE_PAY);
		order.setUserCode(superiorUser.getUserCode());
		orderBiz.addOrder(order);
	}
	/**
	 * 获取支付产品信息
	 * @return
	 */
	@RequestMapping(value="/findProduct")
	@ResponseBody
	public List<ProductVo> findProduct(){
		return productBiz.findProduct(new ProductVo());
	}
	/**
	 * 查询下级用户
	 * @return
	 */
	@RequestMapping(value="/findSubordinate")
	@ResponseBody
	public List<UserVo> findSubordinate(String userCode){
		UserVo userVo = new UserVo();
		userVo.setUserSuperiorCode(userCode);
		userVo.setDeleteFlag(0);
		return userBiz.findUser(userVo);
	}
	/**
	 * 查询用户余额
	 * @return
	 */
	@RequestMapping(value="/findUserMoney")
	@ResponseBody
	public UserVo findUserMoney(String userCode){
		UserVo userVo = new UserVo();
		User user = userBiz.findByCode(userCode);
		Balance balance = balanceBiz.findByUserCode(userCode);
		userVo.setBalance(balance.getUserMoney());
		userVo.setSmsFlag(user.getSmsFlag() == null ? 0 : user.getSmsFlag());
		return userVo;
	}
	/**
	 * 发送短信
	 * @param phoneNum
	 * @return
	 */
	@RequestMapping(value="/smsSend")
	@ResponseBody
	public String smsSend(String phoneNum){
		//获得随机数
		String code = String.valueOf(Math.random()*1000000);
		code = code.substring(0, code.indexOf("."));
		SendSmsResponse response = new SendSmsResponse();
		try {
			response = SmsUtil.sendSms(phoneNum, code);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		if("OK".equals(response.getMessage())){
			return code;
		}else{
			return "发送短信失败";
		}
	}
	/**
	 * 修改用户手机号
	 * @param phoneNum
	 * @return
	 */
	@RequestMapping(value="/updateUserPhoneNum")
	@ResponseBody
	public String updateUserPhoneNum(User user){
		user.setSmsFlag(1);
		userBiz.updateByPhoneNum(user);
		return "验证成功！";
	}
	
	/**
	 * 上传截图
	 * @param declarationVo
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadFiles")
	@ResponseBody
	public String uploadFiles(DeclarationVo declarationVo,HttpServletRequest request){
		String fileName = "";
		if(declarationVo.getUploadImg() != null){
			fileName = UploadImgUtil.dowloadFile(declarationVo.getUploadImg(), request);
		}
		return fileName;
	}
}
